<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Download as DownloadModel;

/**
 * 下载管理控制器
 */
class Download extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see', 'down', 'preview'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['id' => 'ID', 'title' => '标题', 'file_name' => '文件名', 'merchant_id' => '商户号'];

        // 获取查询条件
        $map = $this->getMap();

        $date = date('Y-m-d');
        $old_date = date("Y-m-d", (strtotime(date('Y-m-d')) - 3600 * 24 * 7));
        $or = [];
        if ($this->no_auth) {
            $map[] = ['merchant_id', '=', $this->merchant_id];
            $map[] = ['create_time', 'between time', ["$old_date 00:00:00", "$date 23:59:59"]];
            $or['public'] = ['=', 1];
            unset($search['merchant_id']);
            unset($search['id']);
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = DownloadModel::where($map)->order('create_time desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $all_status = ['正在下载', '下载成功', '下载失败'];
        $items = [
            ['id', 'ID'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['title', '标题'],
            ['file_name', '文件名'],
            ['url', '来源地址'],
            ['count', '下载次数'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['url_type', 'url类型', 'status', '', ['本地', '外链']],
            ['public', '公开', 'status', '', ['NO', 'YES']],
            ['status', '状态', 'status', '', $all_status],
            ['right_button', '操作', 'btn']
        ];
        $hideCheckbox = false;
        if ($this->no_auth) {
            unset($items[1]);
            unset($items[8]);
            $hideCheckbox = true;
        }
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('下载管理') // 设置页面标题
            ->setTableName('payment_download') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,delete') // 批量添加顶部按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButton('down', ['target' => '_blank', 'title' => '下载', 'icon' => 'fa fa-fw fa-arrow-down', 'href' => url('down', ['id' => '__id__'])])
            ->addRightButton('preview', ['target' => '_blank', 'title' => '预览', 'icon' => 'fa fa-fw fa-search-plus', 'href' => url('preview', ['id' => '__id__'])])
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->replaceRightButton(['status' => ['<>', 1]], '', 'down') // 替换右侧按钮
            ->replaceRightButton(['status' => ['<>', 1]], '', 'preview') // 替换右侧按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 下载
     * @return mixed
     */
    public function down($id = null)
    {
        ini_set('memory_limit', '1024M');
        if ($id === null) {
            $this->error('缺少参数！');
        }
        set_time_limit(3600);

        // 获取数据
        $info = DownloadModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        DownloadModel::where('id', $id)->inc('count', 1)->update(['update_time' => time()]);

        if ($info['url_type'] == 0) {
            $file = $this->file_path . $info['file_name'];
        } else {
            $file = $info['file_name'];
        }

        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
        } else {
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='{$file}'";
            echo "</script>";
        }
        exit;
    }

    /**
     * 预览
     * @return mixed
     */
    public function preview($id = null)
    {
        ini_set('memory_limit', '1024M');
        if ($id === null) {
            $this->error('缺少参数！');
        }
        set_time_limit(3600);

        // 获取数据
        $info = DownloadModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('参数错误！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        DownloadModel::where('id', $id)->inc('count', 1)->update(['update_time' => time()]);

        if ($info['url_type'] == 0) {
            $file = $this->file_path . $info['file_name'];
        } else {
            $file = $info['file_name'];
        }

        if (file_exists($file)) {

            $filesize = filesize($file);
            if ($filesize > 2000000) {
                $this->error('预览文件大小不能超过2M', url('index'));
            }

            header("Content-type:text/html;charset=GB2312");

            echo '<table border="1" width="80%" align="center">';
            $row = 1;
            if (($handle = fopen($file, 'r')) !== false) {
                while (($data = fgetcsv($handle, 0, ',')) !== false) {
                    $num = count($data);
                    $row++;
                    echo '<tr>';
                    for ($c = 0; $c < $num; $c++) {
                        echo '<td>' . $data[$c] . '</td>';
                    }
                    echo '</tr>';
                }
                fclose($handle);
            }

            echo '</table>';
        } else {
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='{$file}'";
            echo "</script>";
        }
        exit;
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }
            $data['url'] = request()->module() . '/' . request()->controller() . '/' . request()->action();

            // 验证
            $result = $this->validate($data, 'Download');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            if ($temp = DownloadModel::create($data)) {
                // 记录行为
                action_log('payment_download_add', 'download', $temp['id'], UID, json_encode($temp));
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        $id = date('YmdHis') . rand(100000, 999999);

        $items = [
            ['static', 'id', 'ID', '不可更改', $id, $id],
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['text', 'title', '标题'],
            ['text', 'file_name', '文件名'],
            ['radio', 'url_type', 'url类型', '如果是外链，文件名请输入类似网址', ['本地', '外链'], '1', '', ''],
            ['radio', 'status', '状态', '', ['正在下载', '下载成功', '下载失败'], '1', '', ''],
            ['radio', 'public', '公开下载', '', ['NO', 'YES'], '0', '', ''],
            ['textarea', 'remark', '备注', '', '', '', ''],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->no_auth) {
            unset($items[1]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = DownloadModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $all_status = ['正在下载', '下载成功', '下载失败'];
        $info['programmer_remark'] = format_nice($info['programmer_remark']);
        $items = [
            ['static', 'id', 'ID'],
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'title', '标题'],
            ['static', 'file_name', '文件名'],
            ['radio', 'url_type', 'url类型', '', ['本地', '外链'], '', '', 'disabled'],
            ['static', 'url', '来源地址', ''],
            ['radio', 'status', '状态', '', $all_status, '', '', 'disabled'],
            ['radio', 'public', '公开下载', '', ['NO', 'YES'], '', '', 'disabled'],
            ['textarea', 'remark', '备注[:无]', '', '', '', ''],
            ['textarea', 'programmer_remark', '程序员备注[:无]', '', '', '', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];
        if ($this->role > $this->have_auth) {
            unset($items[9]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id id
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'Download');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            if (DownloadModel::update($data)) {
                $temp = DownloadModel::where(['id' => $data['id']])->find();
                // 记录行为
                action_log('payment_download_edit', 'download', $temp['id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = DownloadModel::where('id', $id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $items = [
            ['static', 'id', 'ID', '不可更改', $id, $id],
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['text', 'title', '标题'],
            ['text', 'file_name', '文件名'],
            ['radio', 'url_type', 'url类型', '如果是外链，文件名请输入类似网址', ['本地', '外链'], '1', '', ''],
            //['text', 'url', '来源地址'],
            ['radio', 'status', '状态', '', ['正在下载', '下载成功', '下载失败'], '1', '', ''],
            ['radio', 'public', '公开下载', '', ['NO', 'YES'], '0', '', ''],
            ['textarea', 'remark', '备注', '', '', '', ''],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = DownloadModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['payment_download_' . $type, 'payment_download', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = DownloadModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_download_edit', 'payment_download', $id, UID, $details]);
    }
}
